package com.smart.lib.service;

import com.smart.lib.entity.BookInfo;
import com.smart.lib.entity.BorrowOrderInfo;
import com.smart.lib.entity.UserBorrowData;
import com.smart.lib.mapper.BorrowMapper;
import com.smart.lib.util.Pager;
import com.smart.lib.util.PagerData;
import com.smart.lib.util.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * 图书借阅实现类
 * */
@Service
public class BorrowService {
    @Autowired
    BorrowMapper borrowMapper;
    @Autowired
    BookService bookService;

    /**
     * 借阅图书
     * @user_id
     * @book_id
     * */
    public Response borrowBook(BorrowOrderInfo borrowOrderInfo){
        // 1. 参数基础校验
        if (borrowOrderInfo == null) {
            return new Response(401, "借阅信息不能为空", null);
        }

        Integer userId = borrowOrderInfo.getUser_id();
        List<Integer> books = borrowOrderInfo.getBooks();

        // 2. 业务参数校验
        if (userId == null || books == null || books.isEmpty()) {
            return new Response(401, "借阅人和借阅书籍不能为空", null);
        }

        // 新增不可借阅图书数量
        Integer errorBorrowCount = 0;

        try {
            // 3. 循环处理每本书的借阅
            for (Integer bookId : books) {
                if (bookId == null) {
                    continue; // 或者返回错误，根据业务需求决定
                }

                BorrowOrderInfo order = new BorrowOrderInfo();
                order.setUser_id(userId);
                order.setBook_id(bookId);

                BookInfo book = new BookInfo();
                //判断当前书籍是否可借阅数
                book.setBook_id(bookId);
                Integer available_copies = bookService.getCurrentBookAvailableCopies(book);
                if(available_copies>0){
                    // 执行添加借阅订单
                    borrowMapper.borrowBook(order);
                    // 更新当前书籍可借阅数量
                    bookService.updateCurrentBookBorrowCopies(book);
                }else{
                    errorBorrowCount +=1;
                }
            }
            if(errorBorrowCount==0){
                return new Response(200, "图书借阅订单添加成功", null);
            }else{
                return new Response(200, "图书借阅订单添加成功,但有"+errorBorrowCount+"本书未成功借阅", null);
            }
        } catch (Exception e) {
            return new Response(500, "图书借阅失败，请稍后重试", null);
        }
    }

    /**
     * 归还图书
     * @user_id
     * @book_id
     * */
    public Response returnBook(BorrowOrderInfo borrowOrderInfo){
        // 1. 参数基础校验
        if (borrowOrderInfo == null) {
            return new Response(401, "还书信息不能为空", null);
        }

        Integer userId = borrowOrderInfo.getUser_id();
        List<Integer> books = borrowOrderInfo.getBooks();

        // 2. 业务参数校验
        if (userId == null || books == null || books.isEmpty()) {
            return new Response(401, "还书人和归还书籍不能为空", null);
        }

        try {
            //循环遍历books里的图书id集合，依次添加订单信息
            for(Integer bookId:books){
                BorrowOrderInfo order = new BorrowOrderInfo();
                order.setUser_id(userId);
                order.setBook_id(bookId);
                //执行修改借阅订单
                borrowMapper.returnBook(order);
                //归还更新当前书籍可借阅数量
                BookInfo book = new BookInfo();
                book.setBook_id(bookId);
                bookService.updateCurrentBookReturnCopies(book);
            }
            return new Response(200,"图书已归还成功",null);
        } catch (Exception e) {
            System.out.println(e);
            return new Response(500, "图书归还失败，请稍后重试", null);
        }
    }

    /**
     * 图书借阅订单分页数据+查询搜索
     * */
    private List<BorrowOrderInfo> getBorrowOrderMapperBySearch(Pager pager){
        Integer currentPage = pager.getCurrentPage();
        Integer startIndex = (currentPage - 1)*pager.getPageSize();
        pager.setStartIndex(startIndex);
        return borrowMapper.getBorrowOrderMapperBySearch(pager);
    }

    /**
     * 图书借阅订单分页数据+查询搜索
     * 查询数据总数
     * */
    private Integer getBorrowOrderMapperCountsBySearch(Pager pager){
        return borrowMapper.getBorrowOrderMapperCountsBySearch(pager);
    }

    /**
     * 手动计算分页
     * */
    private Integer getBorrowOrderPageTotalBySearch(Pager pager){
        Integer borrowOrderTotalCounts = getBorrowOrderMapperCountsBySearch(pager);
        Integer pageTotal = 1;//初始设定当前只有一页
        //数据总条数除以pageSize每页显示条数，如取余数求模，如果有余数，页码+1
        //如果可以整除，则页码等于数据总数除以pageSize
        pageTotal = borrowOrderTotalCounts/pager.getPageSize();
        if(borrowOrderTotalCounts%pager.getPageSize()>0){
            pageTotal += 1;
        }
        return pageTotal;
    }

    /**
     * 根据查询得到借阅订单数据
     * 装载数据给前端
     * */
    public Response getBorrowOrderPagerDataBySearch(Pager pager){
        PagerData pagerData = new PagerData();
        pagerData.setData(getBorrowOrderMapperBySearch(pager));
        pagerData.setPageTotal(getBorrowOrderPageTotalBySearch(pager));
        pagerData.setTotal(getBorrowOrderMapperCountsBySearch(pager));
        return new Response(200,"查询借阅订单数据成功",pagerData);
    }

    /**
     * 今日借阅中的图书数量
     * */
    public Integer getCurrentBorrowTotal(){
        return borrowMapper.getCurrentBorrowTotal();
    }

    /**
     * 总共未归还图书总量，也就是借阅中的数量
     * */
    public Integer getBorrowingTotal(){
        return borrowMapper.getBorrowingTotal();
    }

    /**
     * 获取指定用户借阅历史记录
     * */
    public Response getUserBorrowHistoryData(Pager pager){
        //第一组数据：指定用户总借阅数，当前借阅，逾期次数，准时归还
        UserBorrowData userBorrowData = borrowMapper.getUserBorrowStats(pager);
        //第二组数据：指定用户借阅记录，图书名、借阅日期、应归还日期、实际归还日期、状态分页数据
        PagerData pagerData = getUserBorrowHistoryPagerData(pager);
        HashMap<String,Object> hm = new HashMap<>();
        hm.put("userHistoryStatus",userBorrowData);
        hm.put("userHistoryPagerData",pagerData);
        return new Response(200,"获取数据成功",hm);
    }

    /**
     * 第二组查询结果：指定用户借阅记录，图书名、借阅日期、应归还日期、实际归还日期、状态分页数据
     * */
    private List<BorrowOrderInfo> getUserBorrowHistoryMapper(Pager pager){
        Integer currentPage = pager.getCurrentPage();
        Integer startIndex = (currentPage - 1)*pager.getPageSize();
        pager.setStartIndex(startIndex);
        return borrowMapper.getUserBorrowHistoryMapper(pager);
    }

    /**
     * 第二组查询结果：指定用户借阅记录，图书名、借阅日期、应归还日期、实际归还日期、状态分页总数据
     * */
    private Integer getCountUserBorrowHistoryMapper(Pager pager){
        return borrowMapper.getCountUserBorrowHistoryMapper(pager);
    }

    /**
     * 手动计算页码
     * */
    private Integer getPageTotalUserBorrowHistoryMapper(Pager pager){
        Integer userCountBorrowHistory = getCountUserBorrowHistoryMapper(pager);
        Integer pageTotal = 1;//初始设定当前只有一页
        //数据总条数除以pageSize每页显示条数，如取余数求模，如果有余数，页码+1
        //如果可以整除，则页码等于数据总数除以pageSize
        pageTotal = userCountBorrowHistory/pager.getPageSize();
        if(userCountBorrowHistory%pager.getPageSize()>0){
            pageTotal += 1;
        }
        return pageTotal;
    }

    /**
     * 装载数据
     * */
    private PagerData getUserBorrowHistoryPagerData(Pager pager){
        PagerData pagerData = new PagerData();
        pagerData.setData(getUserBorrowHistoryMapper(pager));
        pagerData.setPageTotal(getPageTotalUserBorrowHistoryMapper(pager));
        pagerData.setTotal(getCountUserBorrowHistoryMapper(pager));
        return pagerData;
    }
}
